package com.gulimall.search.searchImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.utils.R;
import com.guli.common.vo.SkuEsModel;
import com.gulimall.search.conf.EsConfig;
import com.gulimall.search.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregator;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: 朱财艺
 * @date : 2022/01/09
 * @Description:
 */
@Service
public class SearchImpl {

    @Autowired
    private RestHighLevelClient client;

    public R startup(List<SkuEsModel> skuEsModel) throws IOException {
        BulkRequest bulkrequest = new BulkRequest();

        for (SkuEsModel esModel : skuEsModel) {

            IndexRequest request = new IndexRequest("product");
            request.id(esModel.getSkuId()+"");
            String jsonString = JSON.toJSONString(esModel);
            request.source(jsonString, XContentType.JSON);
            bulkrequest.add(request);
        }

        BulkResponse bulk = client.bulk(bulkrequest, RequestOptions.DEFAULT);

         if (bulk.hasFailures()){

             return R.error();
         }

        return R.ok();
    }

    public com.gulimall.search.vo.SearchResponse getSearchResult(SearchParam searchParam) throws IOException {

        com.gulimall.search.vo.SearchResponse searchResponse1 = new com.gulimall.search.vo.SearchResponse();
        SearchSourceBuilder searchSourceBuilder = bulidSearchRequest(searchParam);
        SearchRequest request = new SearchRequest("product");
        request.source(searchSourceBuilder);
        SearchResponse search = client.search(request, EsConfig.COMMON_OPTIONS);
        SearchHits hits = search.getHits();
        long value = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();
        ArrayList<SkuEsModel> searchResponses = new ArrayList<>();
        for (SearchHit hit : hits1) {
            String sourceAsString = hit.getSourceAsString();
            SkuEsModel searchResponse = JSON.parseObject(sourceAsString, SkuEsModel.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("skuTitle");
            if (highlightField!=null){

                String name = highlightField.getName();
                searchResponse.setSkuTitle(name);
            }
            searchResponses.add(searchResponse);
        }
        searchResponse1.setProducts(searchResponses);
        searchResponse1.setTotal(value);
        searchResponse1.setPageNum(searchParam.getPageNum());
        int totalpages=(int)(value/searchParam.getSize());
        int l = (int) (value%searchParam.getSize());
        if (l==0){
            searchResponse1.setTotalPages(totalpages);
        }else {
            searchResponse1.setTotalPages(totalpages+1);
        }

        ArrayList<Integer> integers = new ArrayList<>();
        for (int i = 1; i <= totalpages; i++) {

            integers.add(i);
        }
        searchResponse1.setPageNavs(integers);


        ArrayList<BrandVo> brandVos = new ArrayList<>();
        Aggregations aggregations = search.getAggregations();
        Terms attrIdAgg = aggregations.get("brandAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            BrandVo brandVo = new BrandVo();
            long l1 = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(l1);
            Aggregations aggregations1 = bucket.getAggregations();
            Terms brandNameAgg = aggregations1.get("brandNameAgg");
            List<? extends Terms.Bucket> buckets = brandNameAgg.getBuckets();
            for (Terms.Bucket bucket1 : buckets) {
                String keyAsString = bucket1.getKeyAsString();
                brandVo.setBrandName(keyAsString);
                Aggregations aggregations2 = bucket.getAggregations();
                Terms brandImgAgg = aggregations2.get("brandImgAgg");
                List<? extends Terms.Bucket> buckets1 = brandImgAgg.getBuckets();
                for (Terms.Bucket bucket2 : buckets1) {
                    brandVo.setBrandImg(bucket2.getKeyAsString());
                }
            }
            brandVos.add(brandVo);
        }
        searchResponse1.setBrands(brandVos);
        Terms catalogAgg = aggregations.get("catalogAgg");
        ArrayList<CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            CatalogVo catalogVo = new CatalogVo();
            long l1 = bucket.getKeyAsNumber().longValue();
            catalogVo.setCatalogId(l1);
            Terms catalogNameAgg = bucket.getAggregations().get("catalogNameAgg");
            for (Terms.Bucket catalogNameAggBucket : catalogNameAgg.getBuckets()) {
                catalogVo.setCatalogName(catalogNameAggBucket.getKeyAsString());
            }
           catalogVos.add(catalogVo);
        }
        ArrayList<AttrVo> attrVos = new ArrayList<>();
        searchResponse1.setCatalogs(catalogVos);
        Nested attrs = aggregations.get("attr");
        Aggregations aggregations1 = attrs.getAggregations();
        Terms attrIdAgg1 = aggregations1.get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg1.getBuckets()) {
            AttrVo attrVo = new AttrVo();
            long l1 = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(l1);
            Terms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
            for (Terms.Bucket attrNameAggBucket : attrNameAgg.getBuckets()) {

                String keyAsString = attrNameAggBucket.getKeyAsString();
                attrVo.setAttrName(keyAsString);
                Terms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
                for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {

                    String keyAsString1 = attrValueAggBucket.getKeyAsString();
//                    attrVo.setAttrValue(keyAsString1);
                }
            }
            searchResponse1.setAttrs(attrVos);
        }
        return searchResponse1;
    }

    private SearchSourceBuilder bulidSearchRequest(SearchParam searchParam) {


        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(searchParam.getKeyword())){
           boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }

        if (searchParam.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogid",searchParam.getCatalog3Id()));
        }

        if (searchParam.getBrandId()!=null && searchParam.getBrandId().size()>0){
            boolQueryBuilder.must(QueryBuilders.termQuery("brandId",searchParam.getBrandId()));
        }

        if (StringUtils.isNotBlank(searchParam.getSkuPrice())){
            String[] s = searchParam.getSkuPrice().split("_");
            if (s.length==1){

                if (searchParam.getSkuPrice().startsWith("_")){
                    boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").lte(s[0]));
                }else {
                    boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").gte(s[0]));
                }
            }else {
              boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").gte(s[0]).lte(s[1]));
            }
        }


         boolQueryBuilder.must(QueryBuilders.termQuery("hasStock",true));

        List<String> attrs = searchParam.getAttrs();
        if (attrs!=null&&attrs.size()>0){
            for (String attr : searchParam.getAttrs()) {
                ///4_钛空银:流光幻镜:霓影紫
                BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                //s[0] 4
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrId",s[0]));
                //s[1] 钛空银:流光幻镜:霓影紫
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",s[1].split(":")));
                NestedQueryBuilder attrs1 = QueryBuilders.nestedQuery("attrs", nestedBoolQueryBuilder, ScoreMode.None);
                boolQueryBuilder.must(attrs1);
            }
        }

        searchSourceBuilder.query(boolQueryBuilder);

        Integer pageNum = searchParam.getPageNum();
        searchSourceBuilder.from((pageNum-1)*searchParam.getSize());
        searchSourceBuilder.size(searchParam.getSize());

        if (!StringUtils.isEmpty(searchParam.getKeyword())){

            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

       TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg").field("brandId");
       TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brandNameAgg").field("brandName");
       TermsAggregationBuilder brandImgAgg = AggregationBuilders.terms("brandImgAgg").field("brandImg");
       brandAgg.subAggregation(brandNameAgg);
       brandAgg.subAggregation(brandImgAgg);
       TermsAggregationBuilder catAgg = AggregationBuilders.terms("catalogAgg").field("catalogId");
       TermsAggregationBuilder cataName = AggregationBuilders.terms("catalogNameAgg").field("catalogName");
       catAgg.subAggregation(cataName);
       searchSourceBuilder.aggregation(brandAgg);
       searchSourceBuilder.aggregation(catAgg);

        NestedAggregationBuilder nested = AggregationBuilders.nested("attr", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attrNameAgg").field("attrs.attrName");
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue");
        attrIdAgg.subAggregation(attrNameAgg);
        attrIdAgg.subAggregation(attrValueAgg);

        nested.subAggregation(attrIdAgg);
        searchSourceBuilder.aggregation(nested);

        System.out.println("构建的DSL语句"+searchSourceBuilder.toString());

        return searchSourceBuilder;
    }

    public SearchResult getSearchResult1(SearchParam searchParam) throws IOException {
        SearchRequest searchRequest = new SearchRequest("product");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1.1 关键词keyword查找
        if(StringUtils.isNotBlank(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
        //1.2 有库存
        boolQueryBuilder.must(QueryBuilders.termQuery("hasStock",searchParam.isHasStock()));
        //1.3 价格区间
        if(StringUtils.isNotBlank(searchParam.getSkuPrice()) && searchParam.getSkuPrice().contains("_")){
            //    400_1900 区间     400_ 大于400  _2000 小于2000
            String skuPrice = searchParam.getSkuPrice();
            String[] s = skuPrice.split("_");
            if(skuPrice.startsWith("_")){ // _2000  s[1]
                boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").lte(s[1]));
            } else if(skuPrice.endsWith("_")){
                boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").gte(s[0]));
            }else{
                boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").gte(s[0]).lte(s[1]));
            }
        }
        //1.4 品牌查询
        if(searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0){
            boolQueryBuilder.must(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        //1.5 分类查询
        if(searchParam.getCatalog3Id() != null){
            boolQueryBuilder.must(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }
        //1.6 属性查找
        if(searchParam.getAttrs() != null && searchParam.getAttrs().size()>0){
            for (String attr : searchParam.getAttrs()) {
                ///4_钛空银:流光幻镜:霓影紫
                BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                //s[0] 4
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrId",s[0]));
                //s[1] 钛空银:流光幻镜:霓影紫
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",s[1].split(":")));
                boolQueryBuilder.must(QueryBuilders.nestedQuery("attrs",nestedBoolQueryBuilder, ScoreMode.None));
            }

        }
        //2*************聚合构建========
        //2.1 brandIdAgg 品牌聚合
        TermsAggregationBuilder brandAggregation = AggregationBuilders.terms("brandIdAgg").field("brandId");

        brandAggregation.subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName"));
        brandAggregation.subAggregation(AggregationBuilders.terms("brandImgAgg").field("brandImg"));
        searchSourceBuilder.aggregation(brandAggregation);
        //2.2 cateIdAgg 分类聚合
        TermsAggregationBuilder cateIdAgg = AggregationBuilders.terms("cateIdAgg").field("catalogId");
        cateIdAgg.subAggregation(AggregationBuilders.terms("cateNameAgg").field("catalogName"));
        searchSourceBuilder.aggregation(cateIdAgg);

        //2.3 属性聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attrAgg", "attrs");
        //构建attrId属性子聚合
        TermsAggregationBuilder attrIdAggregation = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        //attrName聚合
        attrIdAggregation.subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"));
        //attrValue聚合
        attrIdAggregation.subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue"));

        nested.subAggregation(attrIdAggregation);
        searchSourceBuilder.aggregation(nested);

        //分页
        searchSourceBuilder.from((searchParam.getPageNum()-1)*searchParam.getSize());
        searchSourceBuilder.size(searchParam.getSize());
        //高亮
        searchSourceBuilder.highlighter(new HighlightBuilder().field("skuTitle").preTags("<span style='color:red'").postTags("</span>"));

        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        //二.执行查询
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);


        //三.处理结果
        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
        long numHits = totalHits.value;
// whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
        TotalHits.Relation relation = totalHits.relation;
        float maxScore = hits.getMaxScore();
        SearchHit[] searchHits = hits.getHits();
        //所有商品信息
        ArrayList<SkuEsModel> products = new ArrayList<>();

        for (SearchHit hit : searchHits) {
            // do something with the SearchHit
            String index = hit.getIndex();
            String id = hit.getId();
            float score = hit.getScore();
            String sourceAsString = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, new TypeReference<SkuEsModel>() {
            });
            skuEsModel.setSkuId(Long.parseLong(id));//赋值主键
            //处理高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlight = highlightFields.get("skuTitle");
            if(highlight != null){
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
                skuEsModel.setSkuTitle(fragmentString);
            }

            products.add(skuEsModel);
        }


        //3 ================处理聚合=================
        Aggregations aggregations = searchResponse.getAggregations();
        //3.1 brandIdAgg 品牌聚合
        ArrayList<BrandVo> brandVos = new ArrayList<>();
        //！！！ 构建聚合时是什么类型 就用什么类型接受
        Terms brandIdAgg = aggregations.get("brandIdAgg");
        for (Terms.Bucket bucket : brandIdAgg.getBuckets()) {
            BrandVo brandVo = new BrandVo();
            //品牌id
            brandVo.setBrandId(bucket.getKeyAsNumber().longValue());
            //获取brandIdAgg聚合的子聚合
            Aggregations bucketAggregations = bucket.getAggregations();
            //品牌名称 //！！！ 构建聚合时是什么类型 就用什么类型接受
            Terms brandNameAgg = bucketAggregations.get("brandNameAgg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            //品牌图片
            Terms brandImgAgg = bucketAggregations.get("brandImgAgg");
            brandVo.setBrandImg(brandImgAgg.getBuckets().get(0).getKeyAsString());
            brandVos.add(brandVo);
        }

        //3.2 cateIdAgg 分类聚合
        ArrayList<CatalogVo> catalogVos = new ArrayList<>();
        //！！！ 构建聚合时是什么类型 就用什么类型接受
        Terms cateIdAggregations = aggregations.get("cateIdAgg");
        for (Terms.Bucket bucket : cateIdAggregations.getBuckets()) {
            CatalogVo catalogVo = new CatalogVo();
            //分类id
            catalogVo.setCatalogId(bucket.getKeyAsNumber().longValue());
            //获取桶的子绝活
            Aggregations bucketAggregations = bucket.getAggregations();
            //分类名称 //！！！ 构建聚合时是什么类型 就用什么类型接受
            Terms cateNameAgg = bucketAggregations.get("cateNameAgg");
            String cateName = cateNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(cateName);
            catalogVos.add(catalogVo);
        }



        //3.3 属性nested聚合处理
        ArrayList<AttrVo> attrVos = new ArrayList<>();

        Nested attrAgg = aggregations.get("attrAgg");
        Aggregations nestedSubAggregations = attrAgg.getAggregations();
        //attrId聚合
        Terms attrIdAgg = nestedSubAggregations.get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            AttrVo attrVo = new AttrVo();
            //属性id
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            //获取子聚合
            Aggregations bucketAggregations = bucket.getAggregations();
            //属性名
            Terms attrNameAgg = bucketAggregations.get("attrNameAgg");
            attrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
            //属性值
            Terms attrValueAgg = bucketAggregations.get("attrValueAgg");
            ArrayList<String> atvs = new ArrayList<>();
            for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                //收集所有value
                atvs.add(attrValueAggBucket.getKeyAsString());
            }
            attrVo.setAttrValue(atvs);
            attrVos.add(attrVo);
        }


        com.gulimall.search.vo.SearchResult searchResult = new com.gulimall.search.vo.SearchResult();
        searchResult.setProducts(products);
        searchResult.setBrands(brandVos);
        searchResult.setCatalogs(catalogVos);
        searchResult.setAttrs(attrVos);
        searchResult.setTotal(numHits);//总数
        //总页数
        int size = searchParam.getSize();
        int totalPage = (int) (numHits%size==0?numHits/size:(numHits/size+1));
        searchResult.setTotalPage(totalPage);
        //页数导航页
        ArrayList<Integer> paNav = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            paNav.add(i);
        }
        searchResult.setPaNav(paNav);
        //当前页
        searchResult.setPageNum(searchParam.getPageNum());
        System.out.println(searchResult);
        return searchResult;
    }
}
